chalk = require 'chalk'
string_width = require 'string-width'
duration_cn = require('duration_cn')

_time = => new Date()-0

{stderr, stdout} = process

class Ingbar
  constructor:(@total, @interval=1000)->
    @_begin = _time()
    @_pre = 0
    @done = 0

  incr:(n=1)->
    @done+=n
    {done,total,_pre,_begin} = @
    now = _time()
    if now - _pre < @interval
      return
    cost = now - _begin
    if done == total or not cost
      return
    @_pre = now
    p = done/total
    remain = (1-p)/p*cost
    speed = done/cost * 60000
    if speed < 1
      speed = Math.round(speed*60)
      speed_unit = "小时"
    else
      speed_unit = "分钟"
      if speed > 10
        speed = Math.round(speed)
      else
        speed = Math.round(speed*100)/100

    left = chalk.gray " #{done} / #{total} │ #{speed} 个/#{speed_unit} "

    right = chalk.gray " 还需 #{duration_cn.msec remain} │ " + chalk.greenBright "#{parseInt(10000*p)/100} %"
    width = string_width(left)+string_width(right)

    mid_len = stdout.columns - width - 2
    if mid_len > 0
      done = parseInt(p * mid_len)
      mid = chalk.gray(
        "├"+"".padEnd(done,">")+"".padEnd(mid_len-done,"─")+"┤"
      )
    else
      mid = chalk.gray "│"
    stderr.write(left+mid+right+"\n")

module.exports = (li)->
  ingbar = new Ingbar(li.length)
  for i from li
    yield i
    ingbar.incr()

module.exports.Ingbar = Ingbar
